package org.jiucheng.magpiebridge.server.aio.proxy;

import java.nio.ByteBuffer;
import java.nio.channels.CompletionHandler;

import org.jiucheng.magpiebridge.protocol.Message;
import org.jiucheng.magpiebridge.server.aio.ServerAttachment;
import org.jiucheng.magpiebridge.server.aio.ServerWriteNoProxyClientReadCompletionHandler;

/**
 * 
 * @author jiucheng
 *
 */
public class ProxyWriteCompletionHandler implements CompletionHandler<Integer, ProxyAttachment> {
    
    public void completed(Integer result, ProxyAttachment attachment) {
        if (attachment.getWriteBuffer().hasRemaining()) {
            attachment.getAsynchronousSocketChannel().write(attachment.getWriteBuffer(), attachment, this);
            return;
        }
        attachment.writed.compareAndSet(true, false);
    }

    public void failed(Throwable exc, ProxyAttachment attachment) {
        attachment.writed.compareAndSet(true, false);
        // exc.printStackTrace();
        if (attachment.getServerAttachment().canWrited()) {
            Message proxym = new Message();
            proxym.setMagic(Message.MAGIC);
            proxym.setType(Message.Type.DISCONNECT);
            proxym.setUri(attachment.getUri());
            ByteBuffer writeBuffer = Message.toByteBuffer(proxym);
            
            attachment.getServerAttachment().getServer().write(writeBuffer, attachment.getServerAttachment().setWriteBuffer(writeBuffer), new ServerWriteNoProxyClientReadCompletionHandler());
        }
        ServerAttachment serverAttachment = attachment.getServerAttachment();
        if (serverAttachment != null) {
        	serverAttachment.close();
        }
    }
}
